package com.mccken.demo.io.nio;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import lombok.extern.slf4j.Slf4j;
    
    /**
     * Created by lilinchao
     * Date 2022/5/24
     * Description ByteBuffer Demo
     */
    @Slf4j
    public class TestByteBuffer {
        public static void main(String[] args){
            /**
             * FileChannel
             * 方式1：输入输出流
             * 方式2：RandomAccessFile
             */
            try (FileChannel channel = new FileInputStream("/Users/mccken/Downloads/temp/2/1.txt").getChannel()){
                //准备缓冲区
                ByteBuffer buffer = ByteBuffer.allocate(10);
                while (true){
                    //1.从 channel 读取数据，向buffer写入
                    int len = channel.read(buffer);
                    log.debug("读取到的字节数:{}",len);
                    if(len == -1){  //判断内容是否读取完
                        break;
                    }
    
                    //打印buffer中的内容
                    buffer.flip(); //2.切换至读模式
                    while (buffer.hasRemaining()){  //是否还有剩余未读数据
                        byte b = buffer.get();	//3.读取数据内容
                        log.debug("实际字节:{}",(char) b);
                    }
                    buffer.clear(); //4.切换到写模式
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }